package com.tanger.log;

import com.tanger.common.jpa.ExampleBuilder;
import com.tanger.common.jpa.PageParams;
import com.tanger.common.jpa.QueryParams;
import com.tanger.common.page.PageList;
import com.tanger.common.result.ActionResult;
import com.tanger.common.utils.BeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * @Description TODO
 * @Author Hchenbin
 * @Date 2024/01/08 16:28
 * @Version 1.0
 */
@Slf4j
@Service
public class SysLogServiceImpl implements SysLogService {

    @Autowired
    private SysLogRepository repository;

    @Override
    public SysLog findOne(Long id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public PageList<SysLog> findAll(PageParams query) {
        Specification specification = ExampleBuilder.builder(BeanUtils.copyProperties(query, new QueryParams()));
        Page<SysLog> page = repository.findAll(specification, query.getPageable());
        PageList<SysLog> result = new PageList<>();
        Optional.ofNullable(page)
                .ifPresent(v -> {
                    result.setRows(v.getContent());
                    result.setTotal(v.getTotalElements());
                    result.setPageTotal(v.getTotalPages());
                    result.setPage(query.getPage());
                    result.setPageSize(query.getSize());
                });
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ActionResult save(SysLog log) {
        repository.save(log);
        return ActionResult.buildResultSuccess("OK");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ActionResult delete(List<Long> ids) {
        repository.deleteAllById(ids);
        return ActionResult.buildResultSuccess("OK");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ActionResult clear() {
        repository.deleteAll();
        return ActionResult.buildResultSuccess("OK");
    }
}
